package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;

    private Mapper mapper;
    private String webappsPath;

    public RequestProcessor(Socket socket, Mapper mapper,String webappsPath) {
        this.socket = socket;
        this.mapper =mapper;
        this.webappsPath =webappsPath;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();
            //封装Request和Response对象，返回html静态资源文件
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            String[] urlStrArr =request.getUrl().split("/");// /demo1/lagou
            String contextName =urlStrArr[1];
            String methodName =urlStrArr[2];
            Host host = mapper.getHostMap().get("localhost");
            if(host.getContextMap().get(contextName) ==null){// 无此工程  跳404
                //输出404
                response.outPut(HttpProtocolUtil.getHttpHeader404());
            }else{
                Context context =host.getContextMap().get(contextName);
                Map<String, HttpServlet> servletMap = context.getWrapper().getServletMap();
                //静态资源处理
                if (servletMap.get("/"+methodName) ==null){
                    response.outPutHtml_v4(webappsPath,request.getUrl());
                }else{
                    //动态资源servlet请求
                    HttpServlet httpServlet =servletMap.get("/"+methodName);
                    httpServlet.service(request,response);
                }
            }

            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
